<template>
  <div class="cart-container">
    <div v-if="loading" class="loading">
      <n-spin size="large" />
    </div>
    <div v-else-if="cartItems.length === 0" class="empty-cart">
      <n-empty description="购物车空空如也">
        <template #extra>
          <n-button type="primary" @click="goToHome">去逛逛</n-button>
        </template>
      </n-empty>
    </div>
    <div v-else class="cart-items">
      <div class="cart-header">
        <n-space justify="space-between" align="center">
          <h2>我的购物车</h2>
          <n-button type="error" @click="handleClearCart">清空购物车</n-button>
        </n-space>
      </div>
      <n-card v-for="item in cartItems" :key="item.id" class="cart-item">
        <n-grid :cols="24" :x-gap="12">
          <n-grid-item :span="4">
            <div class="product-image">
              <n-image 
                width="100%" 
                :src="item.product?.images?.[0] || ''" 
                fallback-src="/placeholder.png"
                object-fit="cover"
              />
            </div>
          </n-grid-item>
          <n-grid-item :span="16">
            <div class="product-info">
              <h3 class="product-name">{{ item.product?.name }}</h3>
              <p class="product-description">{{ item.product?.description }}</p>
              <p class="product-time">添加时间: {{ formatTime(item.createdAt) }}</p>
            </div>
          </n-grid-item>
          <n-grid-item :span="4">
            <div class="product-actions">
              <div class="product-price">¥{{ item.product?.price?.toFixed(2) }}</div>
              <n-button type="error" @click="handleRemoveItem(item.id)">删除</n-button>
            </div>
          </n-grid-item>
        </n-grid>
      </n-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NSpin, NEmpty, NSpace, NCard, NGrid, NGridItem, NImage } from 'naive-ui'
import { useMessage } from 'naive-ui'
import { getCartItems, removeFromCart, clearCart } from '../api/cart'
import { useUserStore } from '../stores/user'
import type { CartItem } from '../api/cart'
import { formatTime } from '../utils/format'

const router = useRouter()
const message = useMessage()
const userStore = useUserStore()
const cartItems = ref<CartItem[]>([])
const loading = ref(true)

onMounted(async () => {
  await fetchCartItems()
})

async function fetchCartItems() {
  try {
    loading.value = true
    const userId = userStore.userInfo?.id
    if (!userId) {
      message.error('请先登录')
      router.push('/login')
      return
    }
    
    const res = await getCartItems({ userId })
    if (res.code === 200) {
      cartItems.value = res.data
    } else {
      message.error(res.message || '获取购物车列表失败')
    }
  } catch (error) {
    console.error('获取购物车列表失败:', error)
    message.error('获取购物车列表失败')
  } finally {
    loading.value = false
  }
}

async function handleRemoveItem(cartItemId: number) {
  try {
    const userId = userStore.userInfo?.id
    if (!userId) {
      message.error('请先登录')
      return
    }
    
    const res = await removeFromCart({ userId, cartItemId })
    if (res.code === 200) {
      message.success('商品已从购物车移除')
      await fetchCartItems()
    } else {
      message.error(res.message || '移除商品失败')
    }
  } catch (error) {
    console.error('移除商品失败:', error)
    message.error('移除商品失败')
  }
}

async function handleClearCart() {
  try {
    const userId = userStore.userInfo?.id
    if (!userId) {
      message.error('请先登录')
      return
    }
    
    const res = await clearCart({ userId })
    if (res.code === 200) {
      message.success('购物车已清空')
      cartItems.value = []
    } else {
      message.error(res.message || '清空购物车失败')
    }
  } catch (error) {
    console.error('清空购物车失败:', error)
    message.error('清空购物车失败')
  }
}

function goToHome() {
  router.push('/')
}
</script>

<style scoped>
.cart-container {
  padding: 16px;
  max-width: 1200px;
  margin: 0 auto;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.empty-cart {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.cart-header {
  margin-bottom: 16px;
}

.cart-item {
  margin-bottom: 16px;
}

.product-image {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-info {
  padding: 0 16px;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: bold;
}

.product-description {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-time {
  margin: 0;
  color: #999;
  font-size: 12px;
}

.product-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  height: 100%;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 16px;
}
</style> 